from django import forms
from django.core.exceptions import ValidationError
from user.models import VSession, Company, WarZone, User
from storehouse.models import Storehouse
import pdb


def token_check(value):
    # 验证token必须存在
    sessionList = VSession.objects.filter(token=value)
    if not sessionList.exists():
        errMsg = 'token Error'
        isValidOk = False
        raise ValidationError(errMsg)
    else:
        session = sessionList[0]


def warZoneId_check(value):
    # 验证战区id必须存在
    if value != -1:
        is_num_by_except(value)
        warZone = WarZone.objects.filter(pk=value)
        if not warZone.exists():
            errMsg = 'warZoneId Error'
            raise ValidationError(errMsg)


def companyId_check(value):
    # 验证单位id必须存在
    if value != -1:
        is_num_by_except(value)
        company = Company.objects.filter(pk=value)
        if not company.exists():
            errMsg = 'companyId Error'
            raise ValidationError(errMsg)


def storehouseId_check(value):
    # 验证仓库id必须存在
    if value != -1:
        is_num_by_except(value)
        storehouse = Storehouse.objects.filter(pk=value)
        if not storehouse.exists():
            errMsg = 'storehouseId Error'
            raise ValidationError(errMsg)


def maxItem_check(value):
    if value < 1:
        errMsg = 'maxItem Error'
        raise ValidationError(errMsg)


def page_check(value):
    if value < 1:
        errMsg = 'page Error'
        raise ValidationError(errMsg)


# def IP_check(value):
#     # 验证IP必须存在
#     IPList = Storehouse.objects.filter(storeIP=value)
#     if not IPList.exists():
#         errMsg = 'IP Error'
#         isValidOk = False
#         raise ValidationError(errMsg)
#     else:
#         storeIP = IPList[0]


def is_num_by_except(num):
    try:
        int(num)
        return True
    except ValueError:
        errMsg = 'value not int'
        raise ValidationError(errMsg)


class StorehouseAddForm(forms.Form):
    storehouseName = forms.CharField(max_length=20)
    storehouseDetails = forms.CharField(max_length=2000)
    storehouseType = forms.CharField(max_length=20)
    storeIP = forms.GenericIPAddressField(required=False)
    storePort = forms.CharField(required=False, max_length=20)
    # token = forms.CharField(max_length=100,validators=[token_check])
    warZoneId = forms.IntegerField(validators=[warZoneId_check])
    companyId = forms.IntegerField(validators=[companyId_check])
    linkName = forms.CharField(max_length=20)
    linkPhone = forms.CharField(max_length=20)

    # def clean_storehouseName(self):
    #     storehouseName = self.cleaned_data['storehouseName']
    #     storehouseName1 = Storehouse.objects.filter(storehouseName = storehouseName)
    #     pdb.set_trace()
    #     if len(storehouseName1) == 1:
    #         errMsg = 'storehouseName is exist'
    #         raise ValidationError(errMsg)
    #     return storehouseName    


class GetStorehouseInfoForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])


class ChangeStorehouseInfoForm(forms.Form):
    storehouseId = forms.IntegerField(validators=[storehouseId_check])
    storehouseName = forms.CharField(max_length=20)
    storehouseDetails = forms.CharField(max_length=2000)
    token = forms.CharField(max_length=100, validators=[token_check])
    warZoneId = forms.IntegerField(validators=[warZoneId_check])
    companyId = forms.IntegerField(validators=[companyId_check])
    linkName = forms.CharField(max_length=20)
    linkPhone = forms.CharField(max_length=20)

    def clean(self):
        token = self.cleaned_data['token']
        sessionList = VSession.objects.filter(token=token)
        if not sessionList.exists():
            errMsg = 'token Error'
            raise ValidationError(errMsg)
        else:
            session = sessionList[0]
            if session.user != None:
                if session.user.userType not in ['2']:
                    errMsg = 'user.userType Error'
                    raise ValidationError(errMsg)
        return self.cleaned_data

    # def clean_storehouseName(self):
    #     storehouseName = self.cleaned_data['storehouseName']
    #     storehouseName1 = Storehouse.objects.filter(storehouseName = storehouseName)
    #     if len(storehouseName1) == 1:
    #         errMsg = 'storehouseName is exist'
    #         raise ValidationError(errMsg)
    #     return storehouseName  


# class GetIPListForm(forms.Form):
#     token = forms.CharField(max_length=100,validators=[token_check])
#     maxItem = forms.IntegerField(validators=[maxItem_check])
#     page = forms.IntegerField(validators=[page_check])


class IPChangeForm(forms.Form):
    token = forms.CharField(required=False, max_length=100, validators=[token_check])
    connectIP = forms.GenericIPAddressField(required=False)
    connectPort = forms.CharField(required=False, max_length=20)
    isMasterStore = forms.CharField(max_length=20, required=False)
    storehouseName = forms.CharField(required=False, max_length=20)
    storehouseDetails = forms.CharField(required=False, max_length=20)
    storeIP = forms.GenericIPAddressField(required=False)
    storePort = forms.CharField(required=False, max_length=20)
    # token = forms.CharField(max_length=100,validators=[token_check])
    linkName = forms.CharField(required=False, max_length=20)
    linkPhone = forms.CharField(required=False, max_length=20)
    warZone = forms.CharField(required=False, max_length=20)
    company = forms.CharField(required=False, max_length=20)
    msg = forms.CharField(required=False, max_length=20)


class GetSubStoreListForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])
    page = forms.IntegerField(validators=[page_check])

    def clean(self):
        token = self.cleaned_data['token']
        sessionList = VSession.objects.filter(token=token)
        if not sessionList.exists():
            errMsg = 'token Error'
            raise ValidationError(errMsg)
        else:
            session = sessionList[0]
            if session.user != None:
                if session.user.userType not in ['2']:
                    errMsg = 'user.userType Error'
                    raise ValidationError(errMsg)
        return self.cleaned_data


class SubStorehouseMsgForm(forms.Form):
    storehouseId = forms.IntegerField(validators=[storehouseId_check])
    token = forms.CharField(max_length=100, validators=[token_check])

    def clean(self):
        token = self.cleaned_data['token']
        sessionList = VSession.objects.filter(token=token)
        if not sessionList.exists():
            errMsg = 'token Error'
            raise ValidationError(errMsg)
        else:
            session = sessionList[0]
            if session.user != None:
                if session.user.userType not in ['2']:
                    errMsg = 'user.userType Error'
                    raise ValidationError(errMsg)
        return self.cleaned_data


class GetWarZoneListForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])
    page = forms.IntegerField(validators=[page_check])


class GetCompanyListForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])
    page = forms.IntegerField(validators=[page_check])
    warZoneId = forms.IntegerField(validators=[warZoneId_check])


class StorehouseOperationForm(forms.Form):
    token = forms.CharField(required=False, max_length=100, validators=[token_check])
    storehouseId = forms.IntegerField(required=False, validators=[storehouseId_check])
    operation = forms.CharField(max_length=20)
    storehouseName = forms.CharField(max_length=20, required=False)
    storeIP = forms.CharField(max_length=20, required=False)
    storePort = forms.CharField(max_length=20, required=False)

    def clean(self):
        operation = self.cleaned_data['operation']
        if operation != '' and (operation not in ['0', '1', '2', '3']):
            errMsg = 'operation Error'
            raise ValidationError(errMsg)
        return self.cleaned_data


class StoreScreenForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    warZoneId = forms.IntegerField(required=False, validators=[warZoneId_check])
    companyId = forms.IntegerField(required=False, validators=[companyId_check])
    runState = forms.CharField(max_length=20, required=False)
    connectstate = forms.CharField(max_length=20, required=False)
    storehouseName = forms.CharField(max_length=20, required=False)
    maxItem = forms.IntegerField(validators=[maxItem_check])
    page = forms.IntegerField(validators=[page_check])

    def clean(self):
        token = self.cleaned_data['token']
        sessionList = VSession.objects.filter(token=token)
        if not sessionList.exists():
            errMsg = 'token Error'
            raise ValidationError(errMsg)
        else:
            session = sessionList[0]
            if session.user != None:
                if session.user.userType not in ['2']:
                    errMsg = 'user.userType Error'
                    raise ValidationError(errMsg)
        return self.cleaned_data


class GetSelectForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])


class WarzoneGetForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    page = forms.IntegerField(validators=[page_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])


class ZoneOptionForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    warZoneId = forms.IntegerField(validators=[warZoneId_check], required=False)
    warZoneState = forms.CharField(max_length=100, required=False)
    name = forms.CharField(max_length=100, required=False)
    option = forms.CharField(max_length=100)

    def clean(self):
        cleaned_data = super(ZoneOptionForm, self).clean()
        option = cleaned_data.get('option')
        warZoneState = cleaned_data.get('warZoneState')
        if option not in ['0', '1', '2']:
            errMsg = 'option Error'
            raise ValidationError(errMsg)
        if warZoneState not in ['', '0', '1']:
            errMsg = 'warZoneState Error'
            raise ValidationError(errMsg)
        return self.cleaned_data

    def clean_name(self):
        name = self.cleaned_data['name']
        warzoneName = WarZone.objects.filter(name=name)
        # pdb.set_trace()
        if len(warzoneName) == 1:
            errMsg = 'name is exist'
            raise ValidationError(errMsg)
        return name


class CompanyGetForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    page = forms.IntegerField(validators=[page_check])
    maxItem = forms.IntegerField(validators=[maxItem_check])
    warZoneId = forms.IntegerField(validators=[warZoneId_check], required=False)


class CompanyOptForm(forms.Form):
    token = forms.CharField(max_length=100, validators=[token_check])
    warZoneId = forms.CharField(validators=[warZoneId_check], required=False)
    state = forms.CharField(max_length=100, required=False)
    name = forms.CharField(max_length=100, required=False)
    option = forms.CharField(max_length=100)
    id = forms.IntegerField(validators=[companyId_check], required=False)

    def clean(self):
        cleaned_data = super(CompanyOptForm, self).clean()
        option = cleaned_data.get('option')
        state = cleaned_data.get('state')
        if option not in ['0', '1', '2']:
            errMsg = 'option Error'
            raise ValidationError(errMsg)
        if state not in ['', '0', '1']:
            errMsg = 'state Error'
            raise ValidationError(errMsg)
        return self.cleaned_data

    def clean_name(self):
        name = self.cleaned_data['name']
        warzoneId = self.cleaned_data['warZoneId']
        # pdb.set_trace()
        if warzoneId not in ['']:
            warzone = WarZone.objects.get(pk=warzoneId)
            companyName = Company.objects.filter(name=name, warZone=warzone, isActive=True)
            # pdb.set_trace()
            if len(companyName) == 1:
                errMsg = 'name is exist'
                raise ValidationError(errMsg)
        return name
